import mongoose from "mongoose";
import { PROVINCE_TYPES } from "../config/constants.mjs";

// 年度数据的子模式
const yearlyDataSchema = new mongoose.Schema({
  year: {
    type: Number,
    required: true,
  },
  value: {
    type: Number,
    required: true,
  },
});

// 统计数据的子模式
const statisticSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    enum: ['GDP', 'income', 'employment', 'cost', 'edFund', 'population'], // 限制统计类型
  },
  unit: {
    type: String,
    required: true,
    enum: ['万元', '元', '万人', '亿元'], // 限制单位类型
  },
  yearlyData: {
    type: [yearlyDataSchema],
    validate: [arrayLimit, '{PATH} 必须至少包含一个数据点'], // 验证至少有一个数据点
  },
});

// 验证函数
function arrayLimit(val) {
  return val.length > 0;
}

// 省份模式
const provinceSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
      unique: true,
      trim: true, // 去除首尾空格
    },
    type: {
      type: String,
      required: true,
      enum: Object.values(PROVINCE_TYPES),
    },
    statistics: {
      type: [statisticSchema],
      required: true,
      validate: [hasRequiredStats, '缺少必要的统计数据'],
    },
  },
  {
    timestamps: true,
  }
);

// 验证必要的统计数据是否存在
function hasRequiredStats(stats) {
  const requiredStats = ['GDP', 'employment', 'population'];
  return requiredStats.every(statName => 
    stats.some(stat => stat.name === statName)
  );
}

// 添加索引以提高查询性能
provinceSchema.index({ name: 1 });
provinceSchema.index({ type: 1 });

export const Province = mongoose.model("Province", provinceSchema);